<?php
namespace Lib\Controller;
//use Lib\Controller\AppController;
use Think\Controller;
use Home\Logic\WxloginLogic;
class HomeBaseController extends Controller{

    private $wxLoginLogic;
    private $UserModel;
    private $AccessTokenModel;
    public function __construct() {
//         $this->wxLoginLogic = new WxloginLogic();
//         $this->UserModel = D('User');
//         $this->AccessTokenModel = D('wx_access_token');
//         if(cookie('wx_access_token')==null){
//             $this->_getWXAccessToken();
//         }
//         if(cookie('userinfo')==null){
//             if(CONTROLLER_NAME.'/'.ACTION_NAME != 'Index/getUserInfo' && cookie('login_jump_url')==null){
//                 cookie('login_jump_url',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME));
//             }
//             session('userinfo',null);
//             $this->_checkWxLogin();
//         }
        parent::__construct();
    }

    public function _checkWxLogin(){
        $code = I("get.code");

        $userInfo = cookie('userinfo');
        if(!$userInfo['id'] && !$code){
            $this->_wxLogin();
        }
    }

    /**
     * 微信登录
     */
    private function _wxLogin(){
        $redirect_uri = 'https://babyvideo.zhfancon.com/index/getUserInfo';
        $this->wxLoginLogic->login($redirect_uri);
    }

    /**
     * 获取weixin_access_token并存入cookie
     */
    public function _getWXAccessToken(){
        $findAccessToken = $this->AccessTokenModel->order('id desc')->find();
        if(!empty($findAccessToken) && $findAccessToken['expires_time'] < time() || empty($findAccessToken)){
            $this->wxLoginLogic->getAccessToken();

            $accessTokenData['wx_access_token'] = cookie("wx_access_token");
            $accessTokenData['create_time'] = time();
            $accessTokenData['expires_time'] = time()+7000;
            $addNewAccessToken = $this->AccessTokenModel->add($accessTokenData);
        }
        else if(!empty($findAccessToken) && $findAccessToken['expires_time'] > time()){
            $token['access_token'] = $findAccessToken['wx_access_token'];
            $expireTime = $findAccessToken['expires_time'] - time();
            cookie('wx_access_token',$token["access_token"],$expireTime);
        }
        return $token;
    }

    /**
     * @param num $status 状态 0 1
     * @param string $info 操作信息
     * @param string $url 跳转路径
     * @param array $array 返回数组
     * @param string $type 回调格式 'JSON' 默认
     */
    public function tmAjaxReturn($status, $info = '', $url = '', $array = array(), $type = 'JSON') {
        $data ['status'] = $status; // 状态
        $data ['info'] = $info; // 提示信息
        $data ['url'] = $url; // 跳转地址
        $data ['data'] = $array; // 返回数据

        $this->ajaxReturn($data, $type);
    }

    //微信post请求
    public function wxCurlPost($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }

    //根据URL地址，下载文件
    public function downAndSaveFile($url,$savePath){
        ob_start();
        readfile($url);
        $img  = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp = fopen($savePath, 'a');
        fwrite($fp, $img);
        fclose($fp);
    }

    /**
     * 查重openid
     * @param unknown $openid
     * @return unknown
     */
    public function checkOpenid($openid,$type="user"){
        $where['openid'] = $openid;
        if($type=='user'){
            $result = $this->UserModel->find_uesr($where,$type="find");
        }
        else if($type=='server'){
            $result = D('server')->where($where)->find();
        }

        if($result){
            $this->checkOpenid(date('YmdHis',time()).rand(1000000,9999999));
        }else{
            return $openid;
        }
    }
    /**
     * 推送微信消息模板
     * @param array $userInfo 用户信息
     * @param array $pushdata 模板数据data
     * @param array $templateid 模板id
     * @param array $color 头标题颜色
     * @param array $data
     */
    public function pushWXMessage($userInfo,$pushdata,$templateid,$orderurl=''){
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".cookie('wx_access_token');

        //封装模板数据
        $pushdata = array(
            'touser' => $userInfo['weixin_openid'],
            'template_id' => $templateid,
            'url' => $orderurl,
            'topcolor' => '#FF0000', //红色
            'data' => $pushdata
        );


        $json_pushdata = json_encode($pushdata);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode($json_pushdata));
        $output = curl_exec($ch);
        curl_close($ch);

        $pushResult = json_decode($output,true);
        if($pushResult['errcode'] == '-1'){
            $this->pushWXMessage($userInfo, $pushdata,$templateid,$orderurl='');
        }
    }

}

?>
